import React, { Component } from 'react';
import { connect } from 'dva';
import { Form, Input, Modal } from 'antd';

@connect((state, ownProps) => {
    const { articles:  { entities } } = state
    const { article_Id } = ownProps
    return {
        ...entities[article_Id],
    } 
})
class Editor extends Component {


    render() {
        const { modalVisible, article_Id, form, handleModalVisible, handleModalUnv } = this.props;
        const okHandle = () => {
            form.validateFieldsAndScroll((err, values) => {
                if (err) return;
                values.id=article_Id;
                // console.log('values is: ' + JSON.stringify(values))
                this.props.dispatch({
                    type: 'articles/updateArticle',
                    payload: values
                })
                handleModalUnv();
            });
        };

        if (modalVisible) {
            if (!article_Id) {
                this.props.dispatch({
                    type: 'articles/getArticleById',
                    articleId: article_Id,
                })
            }
        }

        const { title, content } = this.props
        
        return (
            <Modal
                title="Edit article"
                visible={modalVisible}
                destroyOnClose={true}
                onOk={okHandle}
                okText="Save"
                onCancel={() => handleModalVisible()}
            >
            
                <Form onSubmit={this.submitHandler}>
                    <Form.Item labelCol={{ span: 5 }} wrapperCol={{ span: 15 }} label="Title">
                        {form.getFieldDecorator('title', {
                            rules: [{ 
                                required: true, 
                                message: 'Title not allow null value!' 
                            }],
                            initialValue: title
                        })
                        (<Input name='title' />)}
                    </Form.Item>
                    <Form.Item labelCol={{ span: 5 }} wrapperCol={{ span: 15 }} label="Content"> 
                        {form.getFieldDecorator('content', {
                            rules: [{ 
                                required: true, 
                                message: 'Content not allow null value!' 
                            },
                            {
                                min: 10, 
                                message: 'Least 10 words.'
                            }],
                            initialValue: content
                        })
                        (<Input.TextArea  autosize={{ minRows: 10 }} />)}
                    </Form.Item>
                </Form>
                
            </Modal>
        );
    }
       
        

}

export default Form.create()(Editor)



